<?php
namespace Tbf\Bundle\UpyunBundle\Model;
use \UpYun as BaseUpyun;
use Symfony\Component\Process\Process;
use Tbf\Bundle\UpyunBundle\Exception\UpyunException;

class UpYun
{
    protected $bucketname;
    protected $username;
    protected $password;
    /** @var \UpYun */
    protected $origin;
    protected $endpoint;
    /**
     *
     * @param \UpYun $origin
     */
    public function __construct($bucketname, $username, $password,$endpoint=null)
    {
        $this->bucketname = $bucketname;
        $this->username = $username;
        $this->password = $password;
        $this->endpoint = $endpoint;
        $this->origin = new BaseUpyun($bucketname,$username,$password,$endpoint);
    }
    /**
     * @return UpYun
     */
    public function getOrigin()
    {
        return $this->origin;
    }

    /**
     * 用php上传文件
     * @param  string $upyun_path
     * @param  string $local_path
     * @return void
     */
    public function uploadByPhp($upyun_path,$local_path)
    {
        return $this->uploadContentByPhp($upyun_path,file_get_contents($local_path));
    }
    /**
     * 用php上传内容
     * @param  string $upyun_path
     * @param  string $content 上传内容
     * @return void
     */
    public function uploadContentByPhp($upyun_path,$content)
    {
        //接口bug,$upyun_path 必须以/开头
        if (substr($upyun_path,0,1)!=='/'){
            $upyun_path = '/'.$upyun_path;
        }
        $md5 = md5($content);
        $this->origin->setContentMD5($md5);
        $this->origin->debug = true;
        for ($i = 0; $i < 3; $i++) {
            try {
                $ret = $this->origin->writeFile($upyun_path, $content, true);
                return;
            } catch (\UpYunException $e) {
                $msg = $e->getMessage();
                if ($msg == 'Connection Failed') {
                    continue;
                }
                throw $e;
            }
        }
        throw new \Exception('upyun upload try too many times!');
    }
    public function newUpyunCmd()
    {
        return new UpyunCmd();
    }
    public function runCommandWithGolang(UpyunCmd $upyun_cmd_builder)
    {
        $input = array(
            'BucketName'=>$this->bucketname,
            'UserName'=>$this->username,
            'PassWord'=>$this->password,
            'EndPoint'=>$this->endpoint,
            'CmdList'=>$upyun_cmd_builder->getCmdList()
        );
        $input = json_encode($input);
        $go_path = realpath(__DIR__.'/../Resources/golang/command.go');
        $p = new Process('go run '.$go_path,null,null,$input,1e9);
        $p->run(function ($type,$output){
            echo $output;
        });
        $code = $p->getExitCode();
        if ($code!==0) {
            throw new UpyunException('fail to execute golang script!');
        }
    }
}//class upyun
